package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        // 1.拷贝属性
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 2.设置默认状态
        dish.setStatus(StatusConstant.DISABLE);

        // 2.添加菜品基本属性
        dishMapper.insert(dish);

        // 3.获取 insert 语句生成的主键值
        Long dishId = dish.getId();

        // 4.拿到 dto 中的口味列表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 5.将每个口味设置菜品 id
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor ->
                    flavor.setDishId(dishId));
        }
        // 6.添加菜品口味
        dishFlavorMapper.insertBatch(flavors);
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO pageQueryDTO) {
        // 1.设置分页参数
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());

        // 2.调用 mapper 动态查询，封装
        List<DishVO> dishVOList = dishMapper.pageQuery(pageQueryDTO);

        // 3.解析封装类，转为 Page
        Page<DishVO> page = (Page<DishVO>) dishVOList;

        // 4.返回结果
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        // 1.查询该菜品是否处于启售状态。若是，则不能删除
        Integer count = dishMapper.countLaunchByIds(ids);
        if (count > 0) { // 这批菜品中包含启售菜品
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        // 2.查询菜品是否有关联套餐。若有，则不能删除
        List<Long> smIds = setmealDishMapper.countByDishIds(ids);
        if (!CollectionUtils.isEmpty(smIds)) {   // 有菜品关联了套餐
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 3.删除该菜品的口味
        dishFlavorMapper.deleteByDishIds(ids);

        // 4.删除该菜品
        dishMapper.deleteByIds(ids);
    }

    @Override
    public DishVO getInfoById(Long id) {
        // 1.根据 id 获取菜品基本信息
        Dish dish = dishMapper.getById(id);

        // 2.根据菜品 id 获取菜品口味信息
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        // 3.封装结果，并返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        if (dishFlavors != null) {
            dishVO.setFlavors(dishFlavors);
        }
        return dishVO;
    }

    @Transactional
    @Override
    public void editInfo(DishDTO dishDTO) {
        // 1.拷贝属性，获得 Dish 对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        // 2.修改菜品基本信息
        dishMapper.update(dish);

        // 3.修改菜品口味信息（先删 后改）
        //  3.1 删除菜品原先口味
        dishFlavorMapper.deleteByDishIds(Collections.singletonList(dish.getId()));
        //  3.2 更新菜品口味
        //      3.2.1 给 dto 中的 flavors 赋上 dish_id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavors.forEach(flavor -> {
            flavor.setDishId(dish.getId());
        });
        //  3.3 插入数据
        dishFlavorMapper.insertBatch(dishDTO.getFlavors());
    }

    @Override
    public List<Dish> listByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .build();
        return dishMapper.list(dish);
    }

    @Transactional
    @Override
    public void enableOrDisable(Integer status, Long id) {
        // 1.根据 status 和 id 构造对象
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();

        // 2.启售操作
        if (status == StatusConstant.ENABLE) {
            dishMapper.update(dish);
            return;
        }

        // 3.停售操作
        // 3.1 查询该菜品是否关联套餐
        List<Long> smIds = setmealDishMapper.countByDishIds(Collections.singletonList(id));
        // 3.2 若关联套餐，将所关联的套餐停售
        if (!CollectionUtils.isEmpty(smIds)) {   // 菜品有关联套餐
            setmealMapper.updateStatusBatch(smIds, status, LocalDateTime.now());
        }
        // 3.3 停售菜品
        dishMapper.update(dish);
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        ArrayList<DishVO> dishVOList = new ArrayList<>();

        // 1.获取启售中的菜品
        List<Dish> dishList = dishMapper.list(dish);
        if(CollectionUtils.isEmpty(dishList)) {
            return dishVOList;
        }

        // 2.遍历菜品列表
        for (Dish d : dishList) {
            // 2.1 拷贝属性
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            // 2.2 补全菜品口味
            List<DishFlavor> dishFlavorList = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(dishFlavorList);

            // 2.3 加入到返回数据列表
            dishVOList.add(dishVO);
        }

        // 3.返回数据列表
        return dishVOList;
    }

}
